package com.company.gameclient;

import com.company.Card;
import com.company.GameStateJson;
import com.google.gson.Gson;
import jdk.nashorn.internal.parser.JSONParser;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.*;

public class GameClient {
    private Socket socket;
    private PrintWriter out;
    private BufferedReader in;
    private String playerName;
    private GameState gameState = new GameState();
    private Scanner scanner = new Scanner(System.in);

    public void connect(String serverAddress, int serverPort, String playerName) {
        this.playerName = playerName;

        try {
            socket = new Socket(serverAddress, serverPort);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            // 启动消息监听线程
            new Thread(this::listenToServer).start();

            // 发送玩家名称
            out.println("NAME:" + playerName);

            // 处理用户输入
            handleUserInput();

        } catch (IOException e) {
            System.out.println("无法连接到服务器: " + e.getMessage());
        } finally {
            try {
                if (socket != null) socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void listenToServer() {
        try {
            String response;
            while ((response = in.readLine()) != null) {
                processServerMessage(response);
            }
        } catch (IOException e) {
            System.out.println("与服务器断开连接");
        }
    }

    private void processServerMessage(String message) {
        String[] parts = message.split(":", 2);
        String command = parts[0];
        String data = parts.length > 1 ? parts[1] : "";

        switch (command) {
            case "WELCOME":
                System.out.println("欢迎你，" + data);
                break;
            case "STATE":
                gameState.updateFromJson(data);
                displayGameState();
                break;
            case "CHAT":
                System.out.println("[聊天] " + data);
                break;
            case "GAMEOVER":
                System.out.println("游戏结束！胜利者: " + data);
                break;
            case "ERROR":
                System.out.println("错误: " + data);
                break;
            default:
                System.out.println("服务器: " + message);
        }
    }

    private void handleUserInput() {
        System.out.println("输入命令 (play/pass/chat/exit):");
        while (true) {
            String input = scanner.nextLine().trim();

            if (input.equalsIgnoreCase("exit")) {
                break;
            } else if (input.startsWith("chat ")) {
                out.println("CHAT:" + input.substring(5));
            } else if (input.equalsIgnoreCase("pass")) {
                out.println("PASS");
            } else if (input.startsWith("play ")) {
                out.println("PLAY:" + input.substring(5));
            } else {
                System.out.println("未知命令");
            }
        }
    }

    private void displayGameState() {
        System.out.println("\n=== 游戏状态 ===");
        System.out.println("当前玩家: " + gameState.getCurrentPlayer());
        System.out.println("上一手牌: " + gameState.getLastPlayedCards());
        System.out.println("你的手牌: " + gameState.getPlayerHand(playerName));
        System.out.println("================\n");
    }

    public static void main(String[] args) {
        if (args.length < 3) {
            System.out.println("用法: java GameClient <服务器地址> <端口> <玩家名称>");
            return;
        }

        String serverAddress = args[0];
        int port = Integer.parseInt(args[1]);
        String playerName = args[2];

        GameClient client = new GameClient();
        client.connect(serverAddress, port, playerName);
    }
}

class GameState {
    private String currentPlayer;
    private List<Card> lastPlayedCards = new ArrayList<>();
    private Map<String, List<Card>> playerHands = new HashMap<>();
    private String gameStatus;
    private List<String> players;

    private static final Gson gson = new Gson();

    public void updateFromJson(String json) {
        try {
            // 使用Gson解析JSON
            GameStateJson state = gson.fromJson(json, GameStateJson.class);

            // 更新游戏状态
            this.currentPlayer = state.getCurrentPlayer();
            this.lastPlayedCards = Card.parseCards(state.getLastPlayedCards());
            this.gameStatus = state.getGameStatus();
            this.players = state.getPlayers();

            // 转换玩家手牌
            this.playerHands = new HashMap<>();
            for (Map.Entry<String, List<String>> entry : state.getPlayerHands().entrySet()) {
                playerHands.put(entry.getKey(), Card.parseCards(entry.getValue()));
            }

        } catch (Exception e) {
            System.out.println("解析游戏状态失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // Getter methods
    public String getCurrentPlayer() {
        return currentPlayer;
    }

    public List<Card> getLastPlayedCards() {
        return lastPlayedCards;
    }

    public List<Card> getPlayerHand(String player) {
        return playerHands.getOrDefault(player, new ArrayList<>());
    }
}